package com.slt.linux.util;

import com.alibaba.excel.EasyExcel;
import com.slt.linux.dto.ExcelVo;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/***
 * @author shalongteng
 * @date 2023年08月11日 15:26
 **/
public class EasyExcelUtil<T> {

    public static List<ExcelVo> getExcelVoList() {
        List<ExcelVo> excelVoList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            ExcelVo excelVo = new ExcelVo();
            excelVo.setArea("aaa" + i);
            excelVo.setCategory("bbb" + i);
            excelVoList.add(excelVo);
        }
        return excelVoList;
    }
    /**
     * 导出并下载Excel
     * @param studentList
     * @param fileName
     * @param response
     */
    public void exportExcel(List<T> studentList, Class clazz , String fileName, HttpServletResponse response){
        try {
            //指定响应数据的格式
            response.setContentType("application/vnd.ms-excel");
            //防止乱码
            response.setCharacterEncoding("utf-8");
            //文件名
            String fileName2 = URLEncoder.encode(fileName, "utf-8");
            //告诉浏览器以附件的方式打开（下载）
//            response.setHeader("Content-disposition", "attachment;filename=" + fileName2 + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelVo.class)
                    .sheet(fileName2)
                    .doWrite(studentList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建excel
     */

    public void createExcel(List<T> studentList, Class clazz, String fileName, ByteArrayOutputStream byteArrayOutputStream){
        //文件名
        EasyExcel.write(byteArrayOutputStream,clazz)
                .sheet(fileName)
                .doWrite(studentList);
    }

    public static void main(String[] args) {
        ExcelFactory<ExcelVo> excelFactory = new ExcelFactory();
        //从数据库查询数据
        List<ExcelVo> excelVoList = getExcelVoList();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String fileName = "数据分析表_测试" + new Random().nextInt(10000) + System.currentTimeMillis() + ".xlsx";
        //生成excel
        EasyExcelUtil<ExcelVo> exportEsUtil = new EasyExcelUtil<>();
        exportEsUtil.createExcel(excelVoList, ExcelVo.class, fileName, out);
        System.out.println("dd");
    }
}
